package com.example.myapplication;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MyThread extends Thread{
    private Handler handler;

    public MyThread(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void run() {
        try {
            URL url = new URL("https://www.wanandroid.com/article/list/0/json");
            HttpURLConnection coon = (HttpURLConnection) url.openConnection();
            coon.setRequestMethod("GET");
            coon.setConnectTimeout(5000);
            if (coon.getResponseCode() == 200){
                InputStream inputStream = coon.getInputStream();
                InputStreamReader input = new InputStreamReader(inputStream);
                BufferedReader bf = new BufferedReader(input);
                StringBuffer sbf = new StringBuffer();
                String n;
               while ((n = bf.readLine())!=null){
                    sbf.append(n);
                }
                String str = sbf.toString();
                Message mes = new Message();
                mes.obj = str;
                handler.sendMessage(mes);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
